<template>
  <div class="addContract bg-f2" id="uploadtu7">
    <div class="bg-fff">
      <el-breadcrumb separator-class="el-icon-arrow-right" class="addHead pAll">
        <el-breadcrumb-item :to="{ path: '/contract' }">合同管理</el-breadcrumb-item>
        <el-breadcrumb-item>编辑合同</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- <div class="divideLine"></div> -->
      <el-form
        :model="addContractInfo"
        :rules="addContractRules"
        ref="ruleForm"
        label-width="150px"
        class="demo-ruleForm pAll"
      >
        <el-row>
          <el-col :span="3" class="contracTitle">合同信息：</el-col>
          <el-col :span="10">
            <el-form-item label="合同编号：" prop="htbh">
              <el-input
                class="inputLength"
                placeholder="合同编号"
                clearable
                v-model.trim="addContractInfo.htbh"
              ></el-input>
            </el-form-item>
            <el-form-item label="合同名称：" prop="htmc">
              <el-input
                class="inputLength"
                placeholder="合同名称"
                clearable
                v-model.trim="addContractInfo.htmc"
              ></el-input>
            </el-form-item>
            <el-form-item label="签订日期：" prop="qdrq">
              <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="addContractInfo.qdrq"
                :picker-options="pickerBeginDateBefore"
                @change="qd"
                type="date"
                placeholder="选择日期时间"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="验收日期：" prop="ysrq">
              <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="addContractInfo.ysrq"
                @change="ys"
                type="date"
                placeholder="选择日期时间"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="维保期限" prop="wbqx">
              <el-input-number
                placeholder="请输入"
                size="medium"
                v-model.trim="addContractInfo.wbqx"
                controls-position="right"
                :min="0"
                :max="5 * 12"
              ></el-input-number>
              <span style="margin-left: 10px">个月</span>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="项目名称：" prop="xmmc">
              <el-input
                class="inputLength"
                placeholder="项目名称"
                clearable
                v-model.trim="addContractInfo.xmmc"
              ></el-input>
            </el-form-item>
            <el-form-item label="合同金额：">
              <el-input-number
                v-model.trim="addContractInfo.htje"
                size="medium"
                controls-position="right"
                :min="0"
                :max="999999999999"
              ></el-input-number>
              <span style="margin-left: 15px">元</span>
            </el-form-item>
            <el-form-item label="合同扫描件：">
              <el-upload
                action="#"
                ref="upload"
                accept=".jpg, .jpeg, .png, .JPG, .JPEG, .PNG"
                list-type="picture-card"
                :auto-upload="false"
                :on-change="lalal"
                :file-list="fileList"
                :on-remove="handleRemove"
                :on-preview="handlePictureCardPreview"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt />
              </el-dialog>
              <span class="el-upload__tip">只能上传jpg/png文件，且不超过500mb</span>
              <!-- <div>
              <input
                v-show="false"
                type="file"
                accept="image/*"
                @change="tirggerFile($event)"
                ref="input"
              />
              <div style="width:60px;height:60px;margin-left:10px" @click="openImg">
                <img class="avatar" v-if="imgUrl!=''" :src="imgUrl" />
                <i v-if="imgUrl==''" class="el-icon-plus avatar-uploader-icon"></i>
              </div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
              </div>-->
            </el-form-item>
            <el-form-item label="备注：">
              <el-input
                type="textarea"
                :rows="4"
                resize="none"
                :maxlength="100"
                show-word-limit
                placeholder="备注"
                v-model.trim="addContractInfo.bz"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="3" class="contracTitle">甲乙方信息：</el-col>
          <el-col :span="10">
            <el-form-item label="甲方：" prop="jfmc">
              <el-input
                class="inputLength"
                placeholder="甲方"
                clearable
                v-model.trim="addContractInfo.jfmc"
              ></el-input>
            </el-form-item>
            <el-form-item label="甲方联系人：" prop="jflxr">
              <el-input
                class="inputLength"
                placeholder="甲方联系人"
                clearable
                v-model.trim="addContractInfo.jflxr"
              ></el-input>
            </el-form-item>
            <el-form-item label="甲方联系电话：" prop="lxrdh">
              <el-input
                class="inputLength"
                placeholder="甲方联系电话"
                clearable
                v-model.trim="addContractInfo.lxrdh"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="乙方：" prop="yfmc">
              <el-input
                class="inputLength"
                placeholder="乙方"
                clearable
                v-model.trim="addContractInfo.yfmc"
              ></el-input>
            </el-form-item>
            <el-form-item label="乙方联系人：" prop="yflxr">
              <el-input
                class="inputLength"
                placeholder="乙方联系人"
                clearable
                v-model.trim="addContractInfo.yflxr"
              ></el-input>
            </el-form-item>
            <el-form-item label="乙方联系电话：" prop="yflxdh">
              <el-input
                class="inputLength"
                placeholder="乙方联系电话"
                clearable
                v-model.trim="addContractInfo.yflxdh"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="text-align: right; margin-top: 20px; margin-bottom: 0">
          <el-button @click="cancel" class="btnSizeStyle">取 消</el-button>
          <el-button type="primary" @click="editContract" v-preventReClick class="btnSizeStyle">确 定</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { pinT, upload } from '../../utils/allUrl.js'
import { startLoading, endLoading } from '@/utils/loading.js'
export default {
  data: function() {
    return {
      addContractInfo: {
        htbh: '',
        htmc: '',
        qdrq: '',
        ysrq: '',
        wbrq: '',
        xmmc: '',
        jfmc: '',
        jflxr: '',
        lxrdh: '',
        yfmc: '',
        yflxr: '',
        yflxdh: '',
        htsmj: '',
        bz: '',
        htje: 0
      },
      fileList: [], // 上传文件列表
      //  图片上传
      imgUrl: [],
      dialogVisible: false,
      dialogImageUrl: '', // 预览
      addContractRules: {
        htbh: [
          { required: true, message: '合同编号', trigger: 'blur' },
          { min: 1, message: '合同编号', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9-_]+$/, message: '请输入数字、字母、-、_', trigger: 'blur' }
        ],
        htmc: [
          { required: true, message: '合同名称', trigger: 'blur' },
          { min: 1, message: '合同名称', trigger: 'blur' },
          { pattern: /^([^\*\#\$\%\【\】\!\！\@\￥\$\[\]\{\}\^\&\*\`\~\"\'<>\/])+$/g, message: '不能输入特殊字符', trigger: 'blur' }
        ],
        xmmc: [{ pattern: /^([^\*\#\$\%\【\】\!\！\@\￥\$\[\]\{\}\^\&\*\`\~\"\'<>\/])+$/g, message: '不能输入特殊字符', trigger: 'blur' }],
        qdrq: [
          { required: true, message: '签订日期', trigger: 'blur' },
          { min: 1, message: '签订日期', trigger: 'blur' }
        ],
        ysrq: [
          { required: true, message: '验收日期', trigger: 'blur' },
          { min: 1, message: '验收日期', trigger: 'blur' }
        ],
        wbqx: [
          { required: true, message: '维保日期', trigger: 'blur' },
          { pattern: /^-?[0-9]\d*$/, message: '不能输入小数', trigger: 'blur' }
        ],
        jfmc: [{ pattern: /^([^\*\#\$\%\【\】\!\！\@\￥\$\[\]\{\}\^\&\*\`\~\"\'<>\/])+$/g, message: '不能输入特殊字符', trigger: 'blur' }],
        jflxr: [{ pattern: /^[\u4E00-\u9FA5]+$/g, message: '请输入中文', trigger: 'blur' }],
        lxrdh: [{ pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
        yfmc: [{ pattern: /^([^\*\#\$\%\【\】\!\！\@\￥\$\[\]\{\}\^\&\*\`\~\"\'<>\/])+$/g, message: '不能输入特殊字符', trigger: 'blur' }],
        yflxr: [{ pattern: /^[\u4E00-\u9FA5]+$/g, message: '请输入中文', trigger: 'blur' }],
        yflxdh: [{ pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }]
      },
      pickerBeginDateBefore: {
        // 设置只能选择到今天及以前的日期
        disabledDate(time) {
          return time.getTime() >= Date.now()
        }
      }
    }
  },
  created: function() {
    // this.addContractInfo = this.$route.query.content
    const htbh = this.$route.query.content
    this.getList(htbh)
  },
  methods: {
    async getList(val) {
      let obj = {}
      const params = new URLSearchParams()
      params.append('id', val)
      const { data: res } = await this.$http.post(`${pinT}htgl/list`, params)
      switch (res.code) {
        case '0000':
          res.data.list.forEach(item => {
            if (item.htsmj === null) {
              item.htsmj = ''
            }
            item.htsmj = item.htsmj.split(',')
          })
          res.data.list[0].htsmj.forEach((item, index) => {
            if (item) {
              obj = {
                name: index,
                url: item
              }
              this.fileList.push(obj)
              this.imgUrl = this.fileList
            }
          })
          this.addContractInfo = res.data.list[0]
          break
        default:
          this.addContractInfo = []
          break
      }
    },
    // 签到日期校验
    qd(val) {
      if (val) {
        const dt = new Date()
        const y = dt.getFullYear()
        const m = (dt.getMonth() + 1 + '').padStart(2, 0)
        const d = (dt.getDate() + '').padStart(2, 0)
        const newD = `${y}-${m}-${d}`
        if (newD.replace(/-/g, '') - '' < val.replace(/-/g, '') - '') {
          this.addContractInfo.qdrq = ''
          return this.$message({
            type: 'error',
            message: '签订日期不能大于当前时间',
            center: true
          })
        }
      }
      if (this.addContractInfo.ysrq) {
        if (this.addContractInfo.ysrq.replace(/-/g, '') - '' < val.replace(/-/g, '') - '') {
          this.addContractInfo.qdrq = ''
          this.$message({
            type: 'error',
            message: '验收日期不能小于签订日期',
            center: true
          })
        }
      }
    },
    // 验收日期校验
    ys(val) {
      if (this.addContractInfo.qdrq) {
        if (this.addContractInfo.qdrq.replace(/-/g, '') - '' > val.replace(/-/g, '') - '') {
          this.addContractInfo.ysrq = ''
          this.$message({
            type: 'error',
            message: '验收日期不能小于签订日期',
            center: true
          })
        }
      }
    },
    editContract: function() {
      if (this.addContractInfo.htje === undefined) {
        this.addContractInfo.htje = ''
      } else if (this.addContractInfo.xmmc === undefined) {
        this.addContractInfo.xmmc = ''
      } else if (this.addContractInfo.bz === undefined) {
        this.addContractInfo.bz = ''
      }
      const arr = []
      this.imgUrl.forEach(item => {
        arr.push(item.url)
      })
      const htsmj = arr.join(',')
      const params = new URLSearchParams()
      const id = this.addContractInfo.id
      params.append('id', id)
      params.append('htbh', this.addContractInfo.htbh)
      params.append('htmc', this.addContractInfo.htmc)
      params.append('qdrq', this.addContractInfo.qdrq)
      params.append('ysrq', this.addContractInfo.ysrq)
      params.append('wbqx', this.addContractInfo.wbqx)
      params.append('xmmc', this.addContractInfo.xmmc)
      params.append('htje', this.addContractInfo.htje)
      params.append('htsmj', htsmj)
      params.append('bz', this.addContractInfo.bz)
      params.append('jfmc', this.addContractInfo.jfmc)
      params.append('jflxr', this.addContractInfo.jflxr)
      params.append('lxrdh', this.addContractInfo.lxrdh)
      params.append('yfmc', this.addContractInfo.yfmc)
      params.append('yflxr', this.addContractInfo.yflxr)
      params.append('yflxdh', this.addContractInfo.yflxdh)
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) {
          return false
        } else {
          const { data: res } = await this.$http.post(`${pinT}htgl/update`, params)
          if (res.code === '0014') {
            return
          } else if (res.code !== '0000') {
            return this.$message({
              type: 'error',
              message: res.message,
              center: true
            })
          }
          this.$message({
            type: 'success',
            duration: 5000,
            message: res.message,
            center: true
          })
          this.$router.push('/ContractManage')
        }
      })
    },
    cancel: function() {
      this.$router.push('/contract')
    },
    // 删除图片
    handleRemove(a) {
      const index = this.imgUrl.findIndex(item => item.uid === a.uid)
      this.imgUrl.splice(index, 1)
    },
    // 添加图片
    async lalal(el) {
      let videoSize = el.size / (1024 * 1024) // 转成M格式
      videoSize = videoSize.toFixed(1) // 保留小数点后一位
      if (videoSize > 50) {
        const dele = this.$refs.upload.uploadFiles
        const index = dele.findIndex(item => item.uid === el.uid)
        dele.splice(index, 1)
        // this.$refs.upload.uploadFiles
        return this.$message({
          type: 'error',
          message: '图片超过最大限制50M',
          center: true
        })
      } else {
        startLoading(document.getElementById('uploadtu7'))
        const file = el.raw
        const fd = new FormData()
        let arr = {}
        fd.append('file', file) // 传文件
        fd.append('type', 2) // 传文件
        const { data: res } = await this.$http.post(`${upload}`, fd)
        endLoading()
        if (res.code === '0000') {
          res.data.forEach(item => {
            arr = {
              uid: el.uid,
              url: item
            }
          })
          this.imgUrl.push(arr)
        } else {
          return this.$message({
            type: 'error',
            message: res.message,
            center: true
          })
        }
      }
    },
    // 预览
    handlePictureCardPreview(e) {
      this.dialogImageUrl = e.url
      this.dialogVisible = true
    },
    // tirggerFile: function(event) {
    //   const file = event.target.files[0]
    //   console.log(file)

    //   let url = ''
    //   var reader = new FileReader()
    //   reader.readAsDataURL(file)
    //   // const that = this
    //   reader.onload = e => {
    //     console.log(e)
    //     url = e.target.result.substring(e.target.result.indexOf(',') + 1)
    //     this.imgUrl = 'data:image/png;base64,' + url
    //     // that.$refs['imgimg'].setAttribute('src','data:image/png;base64,'+url);
    //   }
    // },
    openImg: function() {
      this.$refs.input.click()
    }
  }
}
</script>
<style lang="scss" scoped>
// .el-breadcrumb {
//   height: 53px;
//   line-height: 53px;
// }
.divideLine {
  width: 100%;
  height: 0.5px;
  position: absolute;
  left: 0;
  background: #e5e5e5;
}
.el-row {
  padding-top: 20px;
  border-bottom: solid 1px #e5e5e5;
  .contracTitle {
    line-height: 45px;
  }
}
.inputLength {
  width: 288px;
}
.el-input-number {
  width: 221px;
}
// 上传的
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  border: solid 1px #dddddd;
  text-align: center;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
}
</style>
